import _ from 'lodash';

/**
 * 工具类
 * @Author: wenjm
 * @Date: 2018-03-27 14:13:32
 * @Last Modified by: wenjm
 * @Last Modified time: 2021-04-21 12:02:48
 */
var util = _.extend({}, _, {

  isDev() {
    if (process.env.NODE_ENV == 'development') {
      return true;
    }
    return false;
  },
  isProd() {
    if (process.env.NODE_ENV == 'development') {
      return false;
    }
    return true;
  },
  error(e) {
    if (this.isDev()) {
      console.error(e);
    }
  },
  isPromise(obj) {
    if (obj == undefined) {
      return false;
    }
    return _.isObject(obj) && _.isFunction(obj.then);
  },
  random(lenght = 16) {
    var $chars = "ABCDEFGHIJKLMNOPQRSTWVUXYZabcdefghijklmnopqrstwvuxyz123456789";
    var maxPos = $chars.length;
    var result = "";
    for (let i = 0; i < lenght; i++) {
      result += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return result;
  },
  buildArray(value) {
    if (value && _.isArray(value)) {
      return value.distinct();
    } else if (value) {
      return [value];
    } else {
      return [];
    }
  },
  browser() {
    var Browser = {
      name: "",
      version: ""
    };
    var ua = navigator.userAgent.toLowerCase();
    var s;
    (s = ua.match(/msie ([\d.]+)/)) ? Browser.ie = s[1]:
      (s = ua.match(/firefox\/([\d.]+)/)) ? Browser.firefox = s[1] :
      (s = ua.match(/chrome\/([\d.]+)/)) ? Browser.chrome = s[1] :
      (s = ua.match(/opera.([\d.]+)/)) ? Browser.opera = s[1] :
      (s = ua.match(/version\/([\d.]+).*safari/)) ? Browser.safari = s[1] : 0;
    if (Browser.ie) { //Js判断为IE浏览器
      Browser.name = "IE";
      Browser.version = Browser.ie;
      return Browser;
    }
    if (Browser.firefox) { //Js判断为火狐(firefox)浏览器
      Browser.name = "Firefox";
      Browser.version = Browser.firefox;
      return Browser;
    }
    if (Browser.chrome) { //Js判断为谷歌chrome浏览器
      Browser.name = "Chrome";
      Browser.version = Browser.chrome;
      return Browser;
    }
    if (Browser.opera) { //Js判断为opera浏览器
      Browser.name = "Opera";
      Browser.version = Browser.opera;
      return Browser;
    }
    if (Browser.safari) { //Js判断为苹果safari浏览器
      Browser.name = "Safari";
      Browser.version = Browser.safari;
      return Browser;
    }
    return Browser;
  },

  htmlEncode(html) {
    var temp = document.createElement("div");
    (temp.textContent != undefined) ? (temp.textContent = html) : (temp.innerText = html);
    var output = temp.innerHTML;
    temp = null;
    return output;
  },
  htmlDecode(text) {
    var temp = document.createElement("div");
    temp.innerHTML = text;
    var output = temp.innerText || temp.textContent;
    temp = null;
    return output;
  },
  htmlClear(str, length) {
    str = str.replace(/<\/?[^>]*>/g, '');
    str = str.replace(/[ | ]*\n/g, '\n');
    str = str.replace(/\n[\s| | ]*\r/g, '\n');
    str = str.replace(/&nbsp;/ig, ' ');
    str = str.replace(/&emsp;/ig, ' ');
    str = str.replace(/&ldquo;/ig, '"');
    str = str.replace(/&rdquo;/ig, '"');
    return (length && length > 0 && str.length > length) ? str.substr(0, length) + "..." : str;
  },

  toJSON(value) {
    if (_.isObject(value)) {
      return value;
    }
    if (_.isEmpty(value)) {
      return {};
    }
    return JSON.parse(value);
  },

  combineUrl(f, s) {
    if (f == undefined || s == undefined) {
      return f || s;
    } else if (f.endsWith("/") && s.startsWith("/")) {
      return "{0}{1}".format(f.substring(0, f.length - 1), s);
    } else if (f.endsWith("/") || s.startsWith("/")) {
      return "{0}{1}".format(f, s);
    } else {
      return "{0}/{1}".format(f, s);
    }
  },
  getLinePoint(point1, point2, offset) {
    let v = ((point1.y - point2.y) * (point2.x - point1.x - offset)) * 1.0 / (point2.x - point1.x);
    return {
      x: point1.x + offset,
      y: point2.y + v
    }
  },
  walkPoints(point1, point2, offset, timespan, callback) {
    if (point2.x - point1.x - offset > 0) {
      callback(point1);
      let v = this.getLinePoint(point1, point2, offset);
      if (v) {
        callback(v);
        this.walkPoints(v, point2, offset, timespan, callback);
      } else {
        callback(point2);
      }
    } else {
      callback(point1);
      window.setTimeout(() => {
        callback(point2);
      }, timespan);
    }
  },
  parse(expression, args) {
    function parseValue(exp, arg) {
      if (arg == undefined) {
        return "";
      } else if (exp.indexOf(".") > -1) {
        return parseValue(exp.substring(exp.indexOf(".") + 1), arg[exp.substring(0, exp.indexOf("."))]);
      } else {
        let v = arg[exp];
        return v == undefined ? "" : v;
      }
    }

    let rg = new RegExp("\\{(.*?)\\}", "g");
    let result = expression;
    let temp = rg.exec(expression);
    while (temp) {
      result = result.replace(new RegExp(temp[0], 'g'), parseValue(temp[1], args));
      temp = rg.exec(expression);
    }
    return result;
  },
  getDistance(lng1, lat1, lng2, lat2) {
    return Math.round(
      6378.138 * 2 * Math.asin(
        Math.sqrt(
          Math.pow(
            Math.sin(
              (
                lat2 * Math.PI / 180 - lat1 * Math.PI / 180
              ) / 2
            ),
            2
          ) + Math.cos(lat2 * Math.PI / 180) * Math.cos(lat1 * Math.PI / 180) * Math.pow(
            Math.sin(
              (
                lng2 * Math.PI / 180 - lng1 * Math.PI / 180
              ) / 2
            ),
            2
          )
        )
      ) * 1000);
  },

  /*
   * 通过链式结构获取复杂对象的属性
   */
  getAttr(object, chain) {
    chain = chain.replace(/\[(\w+)\]/g, '.$1') // convert indexes to properties
    chain = chain.replace(/^\./, '') // strip a leading dot
    const a = chain.split('.')
    if (a.length == 1 && a[0] === '') {
      return object
    }
    for (let i = 0, n = a.length; i < n; ++i) {
      let k = a[i];
      if (k in object) {
        object = object[k];
      } else {
        return;
      }
    }
    return object
  },
  /*
   * 通过链式结构设置复杂对象的属性
   */
  setAttr(object, chain, value) {
    chain = chain.replace(/\[(\w+)\]/g, '.$1') // convert indexes to properties
    chain = chain.replace(/^\./, '') // strip a leading dot
    let propChain = chain.split('.')
    if (propChain.length === 1) {
      object[propChain[0]] = value
      return
    }
    let first = propChain.shift()
    let second = propChain[0]
    if (!isNaN(+first)) {
      first = +first
    }
    if (!object[first]) {
      if (!isNaN(second)) {
        object[first] = []
      } else {
        object[first] = {}
      }
    }
    this.setAttr(object[first], propChain.join('.'), value)
  },

  getCurrentPage() {
    return getCurrentPages()[getCurrentPages().length - 1];
  },

  getCurrentVM() {
    return this.getCurrentPage().$vm;
  },

  getCurrentController() {
    return this.getCurrentPage().$vm.super;
  },
  serializeObject(obj, parents = []) {
    if (typeof obj === 'string') return obj
    const resultArray = [];
    const separator = '&';
    let newParents;

    function varName(name) {
      if (parents.length > 0) {
        let parentParts = '';
        for (let j = 0; j < parents.length; j += 1) {
          if (j === 0) parentParts += parents[j];
          else parentParts += `[${encodeURIComponent(parents[j])}]`;
        }
        return `${parentParts}[${encodeURIComponent(name)}]`;
      }
      return encodeURIComponent(name);
    }

    function varValue(value) {
      return encodeURIComponent(value);
    }
    Object.keys(obj).forEach((prop) => {
      let toPush;
      if (Array.isArray(obj[prop])) {
        toPush = [];
        for (let i = 0; i < obj[prop].length; i += 1) {
          if (!Array.isArray(obj[prop][i]) && typeof obj[prop][i] === 'object') {
            newParents = parents.slice();
            newParents.push(prop);
            newParents.push(String(i));
            toPush.push(util.serializeObject(obj[prop][i], newParents));
          } else {
            toPush.push(`${varName(prop)}[]=${varValue(obj[prop][i])}`);
          }
        }
        if (toPush.length > 0) resultArray.push(toPush.join(separator));
      } else if (obj[prop] === null || obj[prop] === '') {
        resultArray.push(`${varName(prop)}=`);
      } else if (typeof obj[prop] === 'object') {
        // Object, convert to named array
        newParents = parents.slice();
        newParents.push(prop);
        toPush = util.serializeObject(obj[prop], newParents);
        if (toPush !== '') resultArray.push(toPush);
      } else if (typeof obj[prop] !== 'undefined' && obj[prop] !== '') {
        // Should be string or plain value
        resultArray.push(`${varName(prop)}=${varValue(obj[prop])}`);
      } else if (obj[prop] === '') resultArray.push(varName(prop));
    });
    return resultArray.join(separator);
  },
  // 获取url中全部参数的对象
  getUrlAllParams(href) {
    // 解决乱码问题
    var url = decodeURI(href)
    var res = {}
    var url_data = _.split(url, '?').length > 1 ? _.split(url, '?')[1] : null;
    if (!url_data) return null
    var params_arr = _.split(url_data, '&')
    _.forEach(params_arr, function (item) {
      var key = _.split(item, '=')[0]
      var value = _.split(item, '=')[1]
      res[key] = value
    });
    return res
  },
  toUrlParams(params) {
    let res = [];
    if (params) {
      Object.keys(params).forEach((key) => {
        res.push(`${key}=${encodeURI(params[key])}`);
      });
    }
    return res.join("&");
  },
  padPrefix(str, prefix) {
    if (str && prefix && !str.startsWith(prefix)) {
      return prefix + str;
    }
    return str;
  }

});

export default util;
